package com.fingard.dsp.bank.directbank.cdb01;

import java.util.Calendar;
import java.util.Date;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.util.DateHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

/**
 * Description: [DSP_国开行明细处理类]
 * Created on 19/03/07
 *
 * @author <a href="mailto:zhangxw@fingard.com.cn">ross</a>
 * @version 1.0
 * Copyright (c) 2019 FinGard
 */
public class CDB01Transaction extends CDB01Base implements ITransaction {
    /**
     * 明细流水查询 STTQ0108
     * @param p_req7516
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
        RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
        String tmpRespCode = "";
        String tmpRespInfo = "";
        retAts.writeStart();
        try {
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req7516.getDateFrom());

            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req7516.getDateTo());

            int tmpIntDateFrom = 0;
            int tmpIntDateTo = 0;
            //按自然月循环查询
            while (tmpIntDateFrom <= tmpIntDateTo && tmpRespCode.length() == 0) {
                Calendar tmpClndrStepTo = Calendar.getInstance();
                tmpClndrStepTo.setTime(tmpCalendarFrom.getTime());
                //判断是否跨月
                if (DateHelper.compareMonth(tmpCalendarFrom, tmpCalendarTo) == -1) {
                    //跨月则设置为月末
                    tmpClndrStepTo.set(Calendar.DAY_OF_MONTH, tmpClndrStepTo.getActualMaximum(Calendar.DAY_OF_MONTH));
                } else {
                    tmpClndrStepTo.setTime(tmpCalendarTo.getTime());
                }

                CDB01Header tmpHeader = new CDB01Header();
                tmpHeader.TransCode = "STTQ0108";
                tmpHeader.Fseqno = getQryTransID();

                XmlTextWriter xmlWriter = new XmlTextWriter();
                writeCommonHead(xmlWriter, tmpHeader);
                xmlWriter.writeElementString("BASE_ACCT_NO", p_req7516.actNum);//账号	String(50)	M
                xmlWriter.writeElementString("ACCT_TYPE", getBankConfig().getMapValueByKey("acctTypeMapping", p_req7516.actNum));//账户类型	String(3)	M	请参考公共代码说明账户类型代码表
                xmlWriter.writeElementString("CCY", convertCurToBank(p_req7516.actCur));//币种	String(3)	M	请参考公共代码说明币种代码表
                xmlWriter.writeElementString("START_DATE", p_req7516.dateFrom);//交易起始日期	STRING(8)	C	起始日期、结束日期与核心流水号必输其一
                xmlWriter.writeElementString("END_DATE", p_req7516.dateTo);//交易结束日期	STRING(8)	C	起始日期、结束日期与核心流水号必输其一
                xmlWriter.writeElementString("REF_NO", "");//核心流水号	STRING(50)	C	起始日期、结束日期与核心流水号必输其一
                xmlWriter.writeEndDocument();
                String[] tmpStrRet = sendToBank(xmlWriter.toXmlString(), false);
                if (tmpStrRet[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                    if (tmpBkReader != null) {
                        String tmpRetCode = tmpBkReader.getFirstText("/Packet/Data/Pub/RetCode");
                        String tmpRetMsg = tmpBkReader.getFirstText("/Packet/Data/Pub/RetMsg");
                        if ("0000".equals(tmpRetCode) || "000000".equals(tmpRetCode)) {
                            while (tmpBkReader.read("/Packet/Data/Res/ACCT_ARRAY")) {
                                XElement tmpXElement = tmpBkReader.readedXElement;
                                RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();
                                tmpRetDetail.actArea = p_req7516.actArea;
                                tmpRetDetail.actNum = tmpXElement.getSingleTextNotNull("BASE_ACCT_NO");
                                tmpRetDetail.cur = convertCurToATS(tmpXElement.getSingleTextNotNull("CCY"));
                                tmpRetDetail.tranDate = Format.Date10Format.format(Format.Date8Format.parse(tmpXElement.getSingleTextNotNull("TRAN_DATE")));//交易日期	STRING (8)	O
                                tmpRetDetail.valueDate = tmpRetDetail.tranDate;
                                tmpRetDetail.tranTime = tmpRetDetail.tranDate + " " + tmpXElement.getSingleTextNotNull("TRAN_TIME");//交易时间	STRING(8)	O
                                tmpRetDetail.busType = tmpXElement.getSingleTextNotNull("TRAN_TYPE");//交易类型	STRING (4)	O
                                String tmpCDFlag = tmpXElement.getSingleTextNotNull("CR_DR_MAINT_IND");//借贷标记	STRING(1)	O	D：借 C：贷
                                String tmpAmt = tmpXElement.getSingleTextNotNull("TRAN_AMT");//交易金额	DOUBLE(17,2)	O
                                if ("C".equals(tmpCDFlag)) {
                                    if (tmpAmt.contains("-")) {
                                        tmpRetDetail.cdFlag = "1";
                                    } else {
                                        tmpRetDetail.cdFlag = "2";
                                    }
                                } else if ("D".equals(tmpCDFlag)) {
                                    if (tmpAmt.contains("-")) {
                                        tmpRetDetail.cdFlag = "2";
                                    } else {
                                        tmpRetDetail.cdFlag = "1";
                                    }
                                } else {
                                    tmpRespCode = "-1";
                                    tmpRespInfo = "银行返回借贷标识(" + tmpCDFlag + ")无法识别，请核实！";
                                    break;
                                }
                                tmpRetDetail.tranAmt = tmpAmt.replace("-", "");
                                tmpRetDetail.accBal = tmpXElement.getSingleTextNotNull("ACTUAL_BAL_AMT");//交易后余额	DOUBLE(17,2)	O
                                tmpRetDetail.usage = tmpXElement.getSingleTextNotNull("NARRATIVE");//摘要/附言	STRING(100)	O
                                tmpRetDetail.abstr = pickupAbstr(tmpRetDetail.usage);
                                tmpRetDetail.recAccNum = tmpXElement.getSingleTextNotNull("OTH_BASE_ACCT_NO");//对方账号	STRING(50)	O
                                tmpRetDetail.recAccName = tmpXElement.getSingleTextNotNull("OTH_ACCT_NAME");//对方户名	STRING(50)	O
                                tmpRetDetail.recAccBank = tmpXElement.getSingleTextNotNull("OTH_BRANCH_NAME");//对方账户开户行名称	STRING(60)	O
                                tmpRetDetail.originator = tmpXElement.getSingleTextNotNull("REFERENCE");//核心交易参考号	STRING(240)	O
                                nodeAnalysic(tmpXElement, tmpRetDetail, getCharset());
                                retAts.writeRetDetail(tmpRetDetail);
                            }
                        } else {
                            tmpRespCode = "-1";
                            tmpRespInfo = tmpRetMsg;
                        }
                    } else {
                        tmpRespCode = "-1";
                        tmpRespInfo = tmpSbMsg.toString();
                    }
                } else {
                    tmpRespCode = "-1";
                    tmpRespInfo = tmpStrRet[1];
                }

                tmpCalendarFrom = tmpClndrStepTo;
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            }
        } catch (Exception ex) {
            FGBiz.limitMsg.exception(reqHeader.bankCode, ex);
            tmpRespCode = "-1";
            tmpRespInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }
        if ("-1".equals(tmpRespCode)) {
            retAts = new RetAtsTrans(p_req7516.reqHeader);
            retAts.writeStart();//写返回ATS的统一头部信息
            retAts.writeRespCode(tmpRespCode);
            retAts.writeRespInfo(tmpRespInfo);
        } else if (retAts.getWrittenRdCount() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("交易为空");
        }

        retAts.writeEnd();
        return retAts;
    }

    @Override
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
        Req7516HisTrans tmpReq7516 = new Req7516HisTrans(p_req7515.reqHeader);
        tmpReq7516.actArea = p_req7515.actArea;
        tmpReq7516.actCur = p_req7515.actCur;
        tmpReq7516.actNum = p_req7515.actNum;
        String tmpStrToday = Format.Date8Format.format(new Date());
        tmpReq7516.dateFrom = tmpStrToday;//设置开始时间和结束时间都为当天
        tmpReq7516.dateTo = tmpStrToday;
        return d_7516_HisTrans(tmpReq7516);
    }
}
